//
//  WebImageView.m
//  SmartRoadShow
//
//  Created by Tracy E on 10-9-29.
//  Copyright 2010 simonwang142232@gmail.com. All rights reserved.
//

#import "WebImageView.h"
#import <QuartzCore/QuartzCore.h>
#import "CacheManager.h"
#import "PushedCitys.h"
#import "ArtEvent.h"
#import "SmartRoadShowAppDelegate.h"
#import "Constants.h"
#import "Reachability.h"
#import "extev.h"

#define pushButtonFrame CGRectMake(190, 190, 20, 20)

enum buttonState {
	red,
	gary,
};

@implementation WebImageView
@synthesize titleLabel,detailLabel;

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
		self.layer.contents =(id)[UIImage imageNamed:@"bjKuang.png"].CGImage;
				
		imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 8, 200, 170)];
		imageView.layer.borderWidth = 2;
		imageView.layer.borderColor = [[UIColor whiteColor] CGColor];
		[imageView setBackgroundColor:[UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:0.8]];
		imageView.layer.cornerRadius = 5;
		imageView.layer.masksToBounds = YES;
		[imageView setContentMode:UIViewContentModeScaleAspectFit];
		imageView.image = [UIImage imageNamed:@"noImage.png"];
		[self addSubview:imageView];
		[imageView release];
	
		
		titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 177, 180, 50)];
		[titleLabel setTextAlignment:UITextAlignmentLeft];
		[titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
		[titleLabel setNumberOfLines:0];
		[titleLabel setBackgroundColor:[UIColor clearColor]];
		[self addSubview:titleLabel];
		[titleLabel release];

				
		detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 210, 200, 20)];
		[detailLabel setTextAlignment:UITextAlignmentLeft];
		[detailLabel setFont:[UIFont boldSystemFontOfSize:12]];
		[detailLabel setBackgroundColor:[UIColor clearColor]];
		[self addSubview:detailLabel];
		[detailLabel release];
		
		[self setUserInteractionEnabled:YES];
    }
    return self;
}

- (void)setTag:(NSInteger)theTag{
	tag = theTag;
}


- (void)setPushInfoCity:(ArtEvent *)event{
	
	myEvent = [event retain];
	
	NSString *stationTime = event._endtime;
	NSString *currentTime = [[NSString stringWithFormat:@"%@",[NSDate date]] substringToIndex:10];
	
	BOOL result = [stationTime compare:currentTime] == NSOrderedDescending || [currentTime isEqual:stationTime];
	
	
	if (result) {
		
		UIControl *control = [[UIControl alloc] initWithFrame:CGRectMake(170, 170, 60, 60)];
		[control addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
		[self addSubview:control];
		[control release];
		
		if (![PushedCitys findById:[NSString stringWithFormat:@"%d",event._id]]) {
			ifConcern = NO;
			 star = [UIButton buttonWithType:UIButtonTypeCustom];
			[star setFrame:pushButtonFrame];
			[star setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
			buttonState = gary;
			[star addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
			[self addSubview:star];
		}
		//已经关注的，红色
		else {
			ifConcern = YES;
			star = [UIButton buttonWithType:UIButtonTypeCustom];
			[star setFrame:pushButtonFrame];
			[star setImage:[UIImage imageNamed:@"star_red.png"] forState:UIControlStateNormal];
			buttonState = red;
			[star addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
			[self addSubview:star];
		}
		
	}
	else {
		star = [UIButton buttonWithType:UIButtonTypeCustom];
		[star setFrame:pushButtonFrame];
		[star setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
		buttonState = gary;
		[self addSubview:star];
	}
		
}

- (void)push{
	
	Reachability *internetReach = [Reachability reachabilityForInternetConnection];
	[internetReach startNotifier];	
	NetworkStatus netStatus = [internetReach currentReachabilityStatus];
	
	if (netStatus) {
		NSString* messageStr = (ifConcern == YES)? @"取消": @"加入";
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil
														message:[NSString stringWithFormat: @"您是否将该活动%@时间提醒?", messageStr]
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
		alert.tag = 889;
		[alert show];
		[alert release];
	}
	else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"本功能需要网络支持，请检查网络连接！"
													   delegate:nil cancelButtonTitle:@"确定"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];		
	}
	
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(alertView.tag == 889){
		
		//SmartRoadShowAppDelegate *appDelegate = (SmartRoadShowAppDelegate *)[[UIApplication sharedApplication] delegate];
		//NSString* token = appDelegate.token;
		
		NSString *time = [NSString stringWithFormat:@"%@,%@",myEvent._starttime,myEvent._endtime];

		if(buttonIndex == 0){
			//已经关注过的，取消关注，变成灰色
			if (buttonState == red) {
				ifConcern = NO;
				[star setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
				buttonState = gary;
				
				[PushedCitys deleteById:[NSString stringWithFormat:@"%d",myEvent._id]];
				
				//------------------------------------
				notiInfo = [[InfoMgr alloc]init];
				UILocalNotification *notification1 = (UILocalNotification *)[notiInfo getDataForKey:[NSString stringWithFormat:@"%i",myEvent._id]];
				[[UIApplication sharedApplication]   cancelLocalNotification:notification1];
				[notiInfo deleteDateForKey:[NSString stringWithFormat:@"%i",myEvent._id]];
				[notiInfo release];
				
//				NSURL* url = [NSURL URLWithString:kCancelSendURL];
//				NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
//				[request setTimeoutInterval:30];
//				[request setHTTPMethod:@"POST"];
//				
//				
//				
//				NSString* postStr = [NSString stringWithFormat:@"token=%@&type=2&city=%@&time=%@&sendid=0&title=%@",token, myEvent._city, time,myEvent._title];
//				NSData* postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
//				[request setHTTPBody:postData];
//				
//				NSError *error = nil;
//				NSURLResponse *response = nil;
//				NSData *urlData = [NSURLConnection 
//								   sendSynchronousRequest:request 
//								   returningResponse: &response 
//								   error: &error];
//				
//				NSString *responseString = [[[NSString alloc] initWithData:urlData encoding: NSUTF8StringEncoding] autorelease];		
//				[request release];
//				NSLog(@"%s,%d,request : %@", __FUNCTION__, __LINE__, responseString);
				
			}
			//没有关注过的，关注一下，变成红色
			else if (buttonState == gary) {
				NSLog(@"新增关注");
				ifConcern = YES;
				[star setImage:[UIImage imageNamed:@"star_red.png"] forState:UIControlStateNormal];
				buttonState = red;
				[PushedCitys insertPushedCityWithId:[NSString stringWithFormat:@"%d",myEvent._id] City:myEvent._city Time:time Title:myEvent._title];
				
//				NSString *url_string = kSendURL;	
//				NSURL *url= [NSURL URLWithString:url_string];
//				NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
//				[request setTimeoutInterval: 30];
//				[request setHTTPMethod:@"POST"];
//				
//				
//				NSString *postStr = [NSString stringWithFormat:@"token=%@&type=2&city=%@&time=%@&sendid=1&title=%@", token, myEvent._city, time,myEvent._title]; 
//				NSData* postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
//				[request setHTTPBody:postData];
//				
//				NSError *error = nil;
//				NSURLResponse *response = nil;
//				NSData *urlData = [NSURLConnection 
//								   sendSynchronousRequest:request 
//								   returningResponse: &response 
//								   error: &error];
//				
//				NSString *responseString = [[[NSString alloc] initWithData:urlData encoding: NSUTF8StringEncoding] autorelease];		
//				[request release];
//				NSLog(@"%s,%d,request : %@", __FUNCTION__, __LINE__, responseString);
				
				
				NSString *myDateString = [NSString stringWithFormat:@"%@8:00:00",time];
				NSDateFormatter *inputFormat = [[[NSDateFormatter alloc] init] autorelease];
				[inputFormat setDateFormat:@"yyyy年MM月dd日HH:mm:ss"];
				[inputFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
				NSDate *theDate  = [inputFormat dateFromString:myDateString];
				
				UILocalNotification *notification1=[[UILocalNotification alloc] init];
				notification1.fireDate=theDate;
				notification1.timeZone=[NSTimeZone defaultTimeZone];
				notification1.alertBody=[NSString stringWithFormat:@"%@",myEvent._city];
				notification1.soundName = UILocalNotificationDefaultSoundName;
				
				notiInfo = [[InfoMgr alloc]init];
				[notiInfo saveData:notification1 forKey:[NSString stringWithFormat:@"%i",myEvent._id]];
				[notiInfo release];
				
				[[UIApplication sharedApplication]   scheduleLocalNotification:notification1];
				
				[notification1 release];
				
			}
		}
		
	}
}


- (void)setImage:(NSString *)imageURL{
	
	UIImage *image = [CacheManager getImageAccordingToURLString:imageURL];
	if (image != nil) {
		imageView.image = image;
	}
	
	else{
		NSLog(@"image download");
		ImageDownloader* downLoader = [[[ImageDownloader alloc] init] autorelease];
		downLoader.imageReceiver = self;
		downLoader.imageURLString = imageURL;
		[downLoader startDownloadWithImageURLString:imageURL];
	
		
		UIImage *image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
		[imageView setImage:image1];
		[CacheManager setImage:image1 withImageURLString:imageURL];
    }
	
}



-(void)imageDownloader:(ImageDownloader*)downloader didReceiveImage:(UIImage*)image{

	NSLog(@"image received");
	
	imageView.image = image;
	[CacheManager setImage:image withImageURLString:downloader.imageURLString];
}


- (void)dealloc {
    [super dealloc];
//	[imageView release];
//	[titleLabel release];
//	[detailLabel release];
//    [myEvent release];	
}


@end
